/**
 * 
 */
package com.stylefeng.guns.modular.ueditor;

import java.io.File;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.stylefeng.guns.config.properties.GunsProperties;
import com.stylefeng.guns.core.common.exception.BizExceptionEnum;
import com.stylefeng.guns.core.exception.GunsException;
import com.stylefeng.guns.core.util.FileUtil;
import com.stylefeng.guns.core.util.ResKit;

/**
 * @author lzg
 *
 */
@Controller
public class UeditorController {
	
	
	@Resource
    private GunsProperties gunsProperties;
	
	@RequestMapping(value="/ueditor")
    @ResponseBody
    public Object  ueditor(HttpServletRequest request,MultipartFile upfile) {
		String action = request.getParameter("action");
		System.out.println(action);
		if("config".equals(action)){
			return getConfig();
		}
		//图片，涂鸦，截图
		else if("uploadimage".equals(action)||"uploadscrawl".equals(action)||"uploadimage".equals(action)){
		
			return imgUpload(upfile);
		}
		else if("uploadvideo".equals(action)){//视频
			return imgUpload(upfile);
		}
		else if("uploadfile".equals(action)){//视频
			return imgUpload(upfile);
		}
		else{
			return "参数错误!!";
		}
		
    }

	/**
	 * @return ueitor的 config.json
	 */
	private Object getConfig() {
		String classPathFile = ResKit.getClassPathFile("config.json");
		byte[] bytes = FileUtil.toByteArray(classPathFile);
		String s = new String(bytes);
		Object parse = JSON.parse(s);
		return parse;
	}
	
//    @RequestMapping(value="/imgUpload")
    @ResponseBody
    public Ueditor imgUpload(MultipartFile upfile) {
    	// gunsProperties.getFileUploadPath()的值是d:/guns-upload
    	String path = gunsProperties.getFileUploadPath()+"ueditor/";
    	 getFileUploadPath(path);
    	//后缀名
         Integer postIndex = upfile.getOriginalFilename().lastIndexOf(".");
         String post = upfile.getOriginalFilename().substring(postIndex);
         String vaName = UUID.randomUUID().toString() + post;
    	
        Ueditor ueditor = new Ueditor();
        ueditor.setUrl(vaName);
        ueditor.setOriginal(vaName);
        ueditor.setState("SUCCESS");
        ueditor.setTitle(vaName);
        try {
  		  upfile.transferTo(new File(path+vaName));
        } catch (Exception e) {
        	ueditor.setState("上传失败");
            throw new GunsException(BizExceptionEnum.UPLOAD_ERROR);
        }
        return ueditor;
    }
    
    
    public void getFileUploadPath(String path) {
    	 File file = new File(path);
    	 if(!file.exists()&&!file.isDirectory()){
    		 file.mkdirs();
    	 }
    }
}
